import type { ReportColumnsItem, ReportList } from '../types'
import useInformant from './useInformant'
import { uuid } from '@/utils'

export default function loadList(
  columns: ReportColumnsItem[],
  request: (...arg: any[]) => Promise<any>,
  readonly: boolean,
  option?: {
    fullTransfer?: boolean
    preProcessData?: (...arg: any[]) => void
  },
) {
  const { informant, setInformant } = useInformant()
  const lists = ref<ReportList[]>([
    ...Array(15)
      .fill(1)
      .map(() => ({
        uuid: uuid('temp_'),
        data: [
          ...columns.map(v => ({
            key: v.prop,
            value: '',
            editable: !readonly,
          })),
        ],
      })),
  ])
  const loading = ref(false)

  const transfer = (
    data: any[],
    columns: ReportColumnsItem[],
    readonly: boolean,
  ): ReportList[] => {
    const keys = columns.map(v => v.prop)
    return data.map((v: any) => {
      return {
        uuid: `${v.id}`,
        data: keys.map(key => ({
          key,
          value: String(v[key] || ''),
          editable: !readonly,
        })),
      }
    })
  }

  async function loadList() {
    loading.value = true
    try {
      const { data } = await request()

      if (data.length > 0) {
        option?.preProcessData?.(data)
        if (option?.fullTransfer) {
          lists.value = transfer(data, columns, readonly)
        }
        else {
          const informantData = data.filter(
            (v: any) => v.type === 2,
          )
          informantData[0] && setInformant(informantData[0])

          const listsData = data.filter(
            (v: any) => v.type === 1,
          )
          lists.value = transfer(
            listsData,
            columns,
            readonly,
          )
        }
      }
    }
    finally {
      loading.value = false
    }
  }

  return {
    lists,
    informant,
    loading,

    loadList,
  }
}
